package com.crm.business.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crm.business.admin.service.AdminService;
import com.crm.business.crm.mapper.*;
import com.crm.business.crm.service.*;
import com.crm.business.examine.service.ExamineService;
import com.crm.common.ka.core.feign.admin.entity.AdminConfigBo;
import com.crm.common.ka.core.feign.admin.entity.AdminMessage;
import com.crm.business.utils.ActionRecordUtil;
import com.crm.common.crm.common.CrmModel;
import com.crm.common.crm.constant.CrmCodeEnum;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.constant.FieldEnum;
import com.crm.common.crm.entity.BO.CrmPutinMoneySaveBO;
import com.crm.common.crm.entity.BO.CrmRoiSearchBO;
import com.crm.common.crm.entity.BO.CrmUpdateInformationBO;
import com.crm.common.crm.entity.PO.*;
import com.crm.common.crm.entity.VO.CrmFieldSortVO;
import com.crm.common.crm.entity.VO.CrmModelFiledVO;
import com.crm.common.ka.core.common.Const;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.common.ka.core.exception.CrmException;
import com.crm.common.ka.core.feign.admin.entity.AdminMessageEnum;
import com.crm.business.servlet.ApplicationContextHolder;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.business.utils.UserUtil;
import com.crm.common.utils.StringUtils;
import com.crm.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CrmPutinMoneyServiceImpl extends BaseServiceImpl<CrmPutinMoneyMapper, CrmPutinMoney> implements ICrmPutinMoneyService, CrmPageService {

    @Autowired
    private ICrmPutinStatisticsService crmPutinStatisticsService;

    @Autowired
    private ICrmHeadquartersBusinessBalanceService crmHeadquartersBusinessBalanceService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private CrmHeadquartersBusinessBalanceMapper crmHeadquartersBusinessBalanceMapper;

    @Autowired
    private ICrmNumberSettingService crmNumberSettingService;

    @Autowired
    private ActionRecordUtil actionRecordUtil;

    @Autowired
    private ExamineService examineService;

    @Autowired
    private CrmFieldMapper crmFieldMapper;

    @Autowired
    private CrmPutinMoneyMapper crmPutinMoneyMapper;

    @Autowired
    private ICrmAllianceBusinessBalanceService crmAllianceBusinessBalanceService;

    @Autowired
    private CrmSourceMapper crmSourceMapper;

    @Override
    public String[] appendSearch() {
        return new String[0];
    }

    @Override
    public void setOtherField(Map<String, Object> map) {

    }

    @Override
    public CrmEnum getLabel() {
        return null;
    }

    /**
     * 查询所有字段
     *
     * @return data
     */
    @Override
    public List<CrmModelFiledVO> queryDefaultField() {
        //查询 线索 自定义字段 中 客户来源 作为 投放平台下拉选项
        List<String> sourceList = querySource();
        String source = "";
        if(CollectionUtil.isNotEmpty(sourceList)){
            source = String.join(",",sourceList);
        }
        List<CrmModelFiledVO> filedList = new ArrayList<>();
        //投放平台
        filedList.add(new CrmModelFiledVO("putinPlatform", FieldEnum.SELECT,"投放平台",1).setIsNull(1).setIsUnique(1).setOptions(source).setFormType(FieldEnum.SELECT.getFormType()).setSetting(new ArrayList<>(StrUtil.splitTrim(source, Const.SEPARATOR))));
        //投放金额
        filedList.add(new CrmModelFiledVO("putinMoney", FieldEnum.FLOATNUMBER,"投放金额",1).setIsNull(1).setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        //实际投放金额
        filedList.add(new CrmModelFiledVO("practicalPutinMoney", FieldEnum.FLOATNUMBER,"实际投放金额",1).setIsNull(1).setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        //课程期数
        filedList.add(new CrmModelFiledVO("coursePeriods", FieldEnum.TEXT,"课程期数",1).setIsNull(1).setIsUnique(1).setFormType(FieldEnum.TEXT.getFormType()));
        //投放日期
        filedList.add(new CrmModelFiledVO("putinDate", FieldEnum.TEXT,"投放日期",1).setIsNull(1).setIsUnique(1).setFormType(FieldEnum.TEXT.getFormType()));
        return filedList;
    }

    @Override
    public CrmModel queryById(Integer id) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByIds(List<Integer> ids) {
        Long userId= UserUtil.getUserId();
        List<Long> roleIds= baseMapper.getDeptUserId(userId);
        Map<Integer, BigDecimal> deptDataMap = new HashMap<>();
        for(int i=0;i<ids.size();i++) {
            CrmPutinMoney crmPutinMoney = baseMapper.queryCrmPutinMoneyById(ids.get(i));
            if (roleIds.contains(180189L)) {
                if (crmPutinMoney.getCheckStatus() == 3) {
                    throw new CrmException(CrmCodeEnum.CRM_ROI_CHECKING_STATUS_ERROR);
                }
            } else {
                if (crmPutinMoney.getCheckStatus() != 0 && crmPutinMoney.getCheckStatus() != 2 && crmPutinMoney.getCheckStatus() != 4) {
                    throw new CrmException(CrmCodeEnum.CRM_PUTIN_MONEY_CANNOT_DELETE);
                }
            }
            //删除投放后更新余额
            if (crmPutinMoney.getCheckStatus() == 1) {
                // 消耗-返点-赔付-转出+转入
//                BigDecimal headMoney=new BigDecimal(0).subtract(crmPutinMoney.getPutinCompensateMoney()).subtract(crmPutinMoney.getRollinMoney()).add(crmPutinMoney.getRolloutMoney()).add(crmPutinMoney.getPracticalPutinMoney());
                BigDecimal headMoney=crmPutinMoney.getPracticalPutinMoney().subtract(crmPutinMoney.getPutinCompensateMoney()).subtract(crmPutinMoney.getRollinMoney()).add(crmPutinMoney.getRolloutMoney());
                CrmHeadquartersBusinessBalance crmHeadquartersBusinessBalance = crmHeadquartersBusinessBalanceService.queryDataByDeptId(crmPutinMoney.getDeptId(),crmPutinMoney.getPutinPlatform());
                crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusinessBalance.getBalance().add(headMoney));
                crmHeadquartersBusinessBalanceService.updateById(crmHeadquartersBusinessBalance);
            }
        }
        removeByIds(ids);
    }

    @Override
    public BasePage<CrmPutinMoney> queryPageList(CrmRoiSearchBO search) {
        Integer pageStart = search.getPage() > 0 ? (search.getPage() - 1) * search.getLimit() : 0;
        search.setPageStart(pageStart);
        if (StringUtils.isNotBlank(search.getPutinPlatform())){
            String allPutinPlatform = search.getPutinPlatform();
            search.setPutinPlatforms(allPutinPlatform.split(","));
        }

        List<Integer> deptIdList = new ArrayList<>();
        List<Integer> deptIdValueList = new ArrayList<>();
        deptIdList.addAll(adminService.queryChildDeptId(14861));
        deptIdList.add(14861);
        if(ObjectUtil.isEmpty(search.getDeptIds())){
            if (deptIdList.stream().filter(w-> String.valueOf(w).equals(String.valueOf(UserUtil.getUser().getDeptId()))).findAny().isPresent()){
                //说明有
                deptIdValueList.addAll(adminService.queryChildDeptId(UserUtil.getUser().getDeptId()));
                deptIdValueList.add(UserUtil.getUser().getDeptId());
                search.setDeptIds(deptIdValueList);
            }else{
                //TODO 默认展示总部信息
                search.setDeptIds(deptIdList);
            }
        }

        Integer count = getBaseMapper().queryPageListCount(search);
        if(count == 0){
            BasePage<CrmPutinMoney> basePage = new BasePage<>(search.getPage(),search.getLimit());
            return basePage;
        }

        List<CrmPutinMoney> crmPutinMoneyList = getBaseMapper().queryPageList(search);
        List<CrmPutinMoney> categoryList= getBaseMapper().queryCategory();
//        JSONObject sourceMap = this.crmSourceMapper.querySourceDataGroupByCode();

        for(int i=0;i<crmPutinMoneyList.size();i++){
            for (int j=0;j<categoryList.size();j++){
//                categoryList.get(j).setCategory(String.valueOf(sourceMap.get(categoryList.get(j).getCategories())));
                if (categoryList.get(j).getCategories()==1){
                    categoryList.get(j).setCategory("电商美工");
                }else if (categoryList.get(j).getCategories()==2){
                    categoryList.get(j).setCategory("手绘插画");
                }else if (categoryList.get(j).getCategories()==3){
                    categoryList.get(j).setCategory("影视后期");
                }
                if (crmPutinMoneyList.get(i).getPutinPlatform().equals(categoryList.get(j).getPutinPlatform())){
                    crmPutinMoneyList.get(i).setCategory(categoryList.get(j).getCategory());
                }
            }
        }
        BasePage<CrmPutinMoney> basePage = new BasePage<>(search.getPage(),search.getLimit(),count);
        basePage.setList(crmPutinMoneyList);

        BigDecimal putinMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getPutinMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal rollinMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getRollinMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal rolloutMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getRolloutMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal putinRebatesMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getPutinRebatesMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal practicalPutinMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getPracticalPutinMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal putinCompensateMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getPutinCompensateMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String, BigDecimal> sunMoney=new HashMap<>();
        sunMoney.put("putinMoneySum",putinMoneySum);
        sunMoney.put("rollinMoneySum",rollinMoneySum);
        sunMoney.put("rolloutMoneySum",rolloutMoneySum);
        sunMoney.put("putinRebatesMoneySum",putinRebatesMoneySum);
        sunMoney.put("practicalPutinMoneySum",practicalPutinMoneySum);
        sunMoney.put("putinCompensateMoneySum",putinCompensateMoneySum);
        basePage.setExtraData(sunMoney);

        return basePage;
    }

    @Override
    public BasePage<CrmPutinMoney> queryCheckPageList(CrmRoiSearchBO search) {
        Integer pageStart = search.getPage() > 0 ? (search.getPage() - 1) * search.getLimit() : 0;
        search.setPageStart(pageStart);
        if (StringUtils.isNotBlank(search.getPutinPlatform())){
            String allPutinPlatform = search.getPutinPlatform();
            search.setPutinPlatforms(allPutinPlatform.split(","));
        }

        Integer count = getBaseMapper().queryPageListCount(search);
        if(count == 0){
            BasePage<CrmPutinMoney> basePage = new BasePage<>(search.getPage(),search.getLimit());
            return basePage;
        }

        List<CrmPutinMoney> crmPutinMoneyList = getBaseMapper().queryPageList(search);
        List<CrmPutinMoney> categoryList= getBaseMapper().queryCategory();
//        JSONObject sourceMap = this.crmSourceMapper.querySourceDataGroupByCode();

        for(int i=0;i<crmPutinMoneyList.size();i++){
            for (int j=0;j<categoryList.size();j++){
//                categoryList.get(j).setCategory(String.valueOf(sourceMap.get(categoryList.get(j).getCategories())));
                if (categoryList.get(j).getCategories()==1){
                    categoryList.get(j).setCategory("电商美工");
                }else if (categoryList.get(j).getCategories()==2){
                    categoryList.get(j).setCategory("手绘插画");
                }else if (categoryList.get(j).getCategories()==3){
                    categoryList.get(j).setCategory("影视后期");
                }
                if (crmPutinMoneyList.get(i).getPutinPlatform().equals(categoryList.get(j).getPutinPlatform())){
                    crmPutinMoneyList.get(i).setCategory(categoryList.get(j).getCategory());
                }
            }
        }
        BasePage<CrmPutinMoney> basePage = new BasePage<>(search.getPage(),search.getLimit(),count);
        basePage.setList(crmPutinMoneyList);

        BigDecimal putinMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getPutinMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal rollinMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getRollinMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal rolloutMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getRolloutMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal putinRebatesMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getPutinRebatesMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal practicalPutinMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getPracticalPutinMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal putinCompensateMoneySum = crmPutinMoneyList.stream().filter(dept -> 1 == dept.getCheckStatus()).map(CrmPutinMoney::getPutinCompensateMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        Map<String, BigDecimal> sunMoney=new HashMap<>();
        sunMoney.put("putinMoneySum",putinMoneySum);
        sunMoney.put("rollinMoneySum",rollinMoneySum);
        sunMoney.put("rolloutMoneySum",rolloutMoneySum);
        sunMoney.put("putinRebatesMoneySum",putinRebatesMoneySum);
        sunMoney.put("practicalPutinMoneySum",practicalPutinMoneySum);
        sunMoney.put("putinCompensateMoneySum",putinCompensateMoneySum);
        basePage.setExtraData(sunMoney);

        return basePage;
    }

    public List<CrmPutinMoney> queryNewList(CrmPutinMoney crmPutinMoney) {
        QueryWrapper<CrmPutinMoney> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(crmPutinMoney.getCoursePeriods())){
            queryWrapper.eq("course_periods",crmPutinMoney.getCoursePeriods());
        }
        if(StringUtils.isNotBlank(crmPutinMoney.getPutinPlatform())){
            queryWrapper.eq("putin_platform",crmPutinMoney.getPutinPlatform());
        }
        if(null != crmPutinMoney.getPutinDate()){
            queryWrapper.eq("putin_date",crmPutinMoney.getPutinDate());
        }
        List<CrmPutinMoney> list = baseMapper.selectList(queryWrapper);
//        BasePage<Map<String, Object>> basePage = queryList(search);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpdate(CrmPutinMoneySaveBO crmModel) {
        CrmPutinMoney crmPutinMoney = BeanUtil.copyProperties(crmModel.getEntity(), CrmPutinMoney.class);
        CrmPutinMoney crmPutinMoneyData ;
        int category =getBaseMapper().queryCategor(String.valueOf(crmModel.getEntity().get("putinPlatform")));
        crmPutinMoney.setCategories(category);
        if(null != crmPutinMoney.getPutinMoneyId()){
            CrmPutinMoney old = getBaseMapper().queryPutinMoneyDataById(crmPutinMoney.getPutinMoneyId());
            if(null == old){
                throw new CrmException(CrmCodeEnum.CRM_PUTIN_MONEY_NOT_ISEXIST);
            }
        }
        //根据投放平台与课程期数与投放日期查询投放金额数据
        crmPutinMoneyData = queryPutinDataByPlatformAndPeriodsAndDate(crmPutinMoney.getPutinPlatform(),crmPutinMoney.getCoursePeriods(),crmPutinMoney.getPutinDate(),crmPutinMoney.getPutinMoneyId());
        if(crmPutinMoneyData != null){
            throw new CrmException(CrmCodeEnum.CRM_PUTIN_MONEY_PLATFORM_AND_COURSEPERIODS_ISEXIST);
        }
        /*ExamineRecordSaveBO examineRecordSaveBO = crmModel.getExamineFlowData();
        examineRecordSaveBO.setOptionalList(new ArrayList<>());
        examineRecordSaveBO.setDataMap(new HashMap<>());
        ExamineRecordReturnVO examineData = null;*/

        // 组织Id为空时默认为营销中心
        if(ObjectUtil.isEmpty(crmPutinMoney.getDeptId())){
            crmPutinMoney.setDeptId(14861);
        }

        // 总部投放设置审核状态为已通过
        crmPutinMoney.setCheckStatus(1);

        if(crmPutinMoney.getPutinMoneyId() != null){
            //关联余额
            CrmHeadquartersBusinessBalance crmHeadquartersBusinessBalance=crmHeadquartersBusinessBalanceMapper.queryDataBySource(crmPutinMoney.getPutinPlatform(),crmPutinMoney.getDeptId());
            if (crmHeadquartersBusinessBalance==null && crmPutinMoney.getPutinMoney().compareTo(crmPutinMoney.getPracticalPutinMoney())==-1 ){
                throw new CrmException(CrmCodeEnum.CRM_HEADQUARTERS);
            }
            /*BigDecimal practical = crmHeadquartersBusinessBalance.getBalance().add(crmPutinMoney.getPutinCompensateMoney()).add(crmPutinMoney.getRollinMoney()).subtract(crmPutinMoney.getRolloutMoney()).subtract(crmPutinMoney.getPracticalPutinMoney());

            if (crmHeadquartersBusinessBalance==null || practical.doubleValue() < 0 ){
                throw new CrmException(CrmCodeEnum.CRM_HEADQUARTERS);
            }*/
            //修改更新时间
            crmPutinMoney.setUpdateTime(DateUtil.date());

//            actionRecordUtil.updateRecord(BeanUtil.beanToMap(baseMapper.queryPutinMoneyDataById(crmPutinMoney.getPutinMoneyId())),BeanUtil.beanToMap(crmPutinMoney),CrmEnum.ROI_INVESTMENT,crmPutinMoney.getNumber(),crmPutinMoney.getPutinMoneyId());

            // 获取旧数据
            CrmPutinMoney oldPutinMoney = this.baseMapper.queryCrmPutinMoneyById(crmPutinMoney.getPutinMoneyId());

            //更新投放数据信息
            baseMapper.updateById(crmPutinMoney);

            // 余额+赔付金额+转入金额-转出金额-消耗金额
            if (crmHeadquartersBusinessBalance!=null) {
                // 旧数据余额回退  余额-赔付-转入+转出+消耗
                BigDecimal oldPractical = new BigDecimal(0).subtract(oldPutinMoney.getPutinCompensateMoney()).subtract(oldPutinMoney.getRollinMoney()).add(oldPutinMoney.getRolloutMoney()).add(oldPutinMoney.getPracticalPutinMoney());
                CrmHeadquartersBusinessBalance oldHeadquartersBusinessBalance=crmHeadquartersBusinessBalanceMapper.queryDataBySource(oldPutinMoney.getPutinPlatform(),oldPutinMoney.getDeptId());
                oldHeadquartersBusinessBalance.setBalance(oldHeadquartersBusinessBalance.getBalance().add(oldPractical));
                crmHeadquartersBusinessBalanceService.updateById(oldHeadquartersBusinessBalance);
                crmHeadquartersBusinessBalance = crmHeadquartersBusinessBalanceMapper.queryDataBySource(crmPutinMoney.getPutinPlatform(),crmPutinMoney.getDeptId());
                //实际消耗    余额+赔付金额+转入金额-转出金额-消耗金额
                /*BigDecimal headMoney=crmPutinMoney.getPracticalPutinMoney().subtract(crmPutinMoney.getPutinRebatesMoney()).
                        subtract(crmPutinMoney.getPutinCompensateMoney()).subtract(crmPutinMoney.getRolloutMoney()).add(crmPutinMoney.getRollinMoney());
                crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusinessBalance.getBalance().subtract(headMoney));*/
                BigDecimal xiaoHao = crmPutinMoney.getPutinCompensateMoney().add(crmPutinMoney.getRollinMoney()).subtract(crmPutinMoney.getRolloutMoney()).subtract(crmPutinMoney.getPracticalPutinMoney());
                BigDecimal money = crmHeadquartersBusinessBalance.getBalance().add(xiaoHao);
                crmHeadquartersBusinessBalance.setBalance(money);
                if(money.doubleValue() < 0){
                    throw new CrmException(CrmCodeEnum.CRM_HEADQUARTERS);
                }
                crmHeadquartersBusinessBalanceService.updateById(crmHeadquartersBusinessBalance);
            }


            //流程审批
            /*if (crmPutinMoney.getCheckStatus() == null || crmPutinMoney.getCheckStatus() != 5){
                if (examineRecordSaveBO != null){
                    this.supplementFieldInfo(12, crmPutinMoney.getPutinMoneyId(), null, examineRecordSaveBO);
                    examineRecordSaveBO.setTitle(crmPutinMoney.getNumber());
                    examineData = examineService.addExamineRecord(examineRecordSaveBO).getData();
                    crmPutinMoney.setExamineRecordId(examineData.getRecordId());
                    crmPutinMoney.setCheckStatus(examineData.getExamineStatus());
                } else {
                    crmPutinMoney.setCheckStatus(0);
                }
            }else{
                //设置审核状态为待审核
                crmPutinMoney.setCheckStatus(0);
            }*/

            updateById(crmPutinMoney);
        }else{//新增
            //关联余额
            CrmHeadquartersBusinessBalance crmHeadquartersBusinessBalance=crmHeadquartersBusinessBalanceMapper.queryDataBySource(crmPutinMoney.getPutinPlatform(),crmPutinMoney.getDeptId());
            BigDecimal practical = crmHeadquartersBusinessBalance.getBalance().add(crmPutinMoney.getPutinCompensateMoney()).add(crmPutinMoney.getRollinMoney()).subtract(crmPutinMoney.getRolloutMoney()).subtract(crmPutinMoney.getPracticalPutinMoney());
            if (crmHeadquartersBusinessBalance==null || practical.doubleValue() < 0 ){
                throw new CrmException(CrmCodeEnum.CRM_HEADQUARTERS);
            }

            //设置系统编号
            List<AdminConfigBo> configList = adminService.queryConfigByName("numberSetting");
            AdminConfigBo adminConfig = configList.stream().filter(config -> Objects.equals("19", config.getValue())).collect(Collectors.toList()).get(0);
            if (adminConfig.getStatus() == 1 && StrUtil.isEmpty(crmPutinMoney.getNumber())) {
                String result = crmNumberSettingService.generateNumber(adminConfig, null);
                if(BeanUtil.isEmpty(crmPutinMoney.getNumber())){
                    crmPutinMoney.setNumber(result);
                }
            }
            Integer count = lambdaQuery().eq(CrmPutinMoney::getNumber, crmPutinMoney.getNumber()).ne(CrmPutinMoney::getCheckStatus, 7).count();
            if (count != null && count > 0) {
                throw new CrmException(CrmCodeEnum.CRM_RECEIVABLES_NUM_ERROR);
            }
            //添加创建时间
            crmPutinMoney.setCreateTime(DateUtil.date());
            //设置录入人为当前登录人
            crmPutinMoney.setPutinUserId(String.valueOf(UserUtil.getUserId()));
            save(crmPutinMoney);

            // 余额+赔付金额+转入金额-转出金额-消耗金额
            if (crmHeadquartersBusinessBalance!=null) {

                //实际消耗    余额+赔付金额+转入金额-转出金额-消耗金额
                /*BigDecimal headMoney=crmPutinMoney.getPracticalPutinMoney().subtract(crmPutinMoney.getPutinRebatesMoney()).
                        subtract(crmPutinMoney.getPutinCompensateMoney()).subtract(crmPutinMoney.getRolloutMoney()).add(crmPutinMoney.getRollinMoney());
                crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusinessBalance.getBalance().subtract(headMoney));*/
                BigDecimal xiaoHao = crmPutinMoney.getPutinCompensateMoney().add(crmPutinMoney.getRollinMoney()).subtract(crmPutinMoney.getRolloutMoney()).subtract(crmPutinMoney.getPracticalPutinMoney());
                crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusinessBalance.getBalance().add(xiaoHao));
                if(crmHeadquartersBusinessBalance.getBalance().doubleValue() < 0){
                    throw new CrmException(CrmCodeEnum.CRM_HEADQUARTERS);
                }
                crmHeadquartersBusinessBalanceService.updateById(crmHeadquartersBusinessBalance);
            }


            AdminMessage adminMessage = new AdminMessage();
            //获取接收人
            List<Long> list=crmPutinMoneyMapper.getRecipient();
            for (int lon =0;lon< list.size()-1;lon++){
                adminMessage.setRecipientUser(list.get(lon));
                adminMessage.setCreateUser(UserUtil.getUserId());
                adminMessage.setCreateTime(crmPutinMoney.getCreateTime());
                adminMessage.setType(AdminMessageEnum.CRM_PUTINMONEY_EXAMINE.getType());
                adminMessage.setLabel(6);
                adminMessage.setTypeId(crmPutinMoney.getPutinMoneyId());
                adminMessage.setTitle(crmPutinMoney.getNumber());
                adminService.saveOrUpdateMessage(adminMessage);
            }
            //流程审批
            /*if (crmPutinMoney.getCheckStatus() == null || crmPutinMoney.getCheckStatus() != 5){
                if (examineRecordSaveBO != null){
                    this.supplementFieldInfo(12, crmPutinMoney.getPutinMoneyId(), null, examineRecordSaveBO);
                    examineRecordSaveBO.setTitle(crmPutinMoney.getNumber());
                    examineData = examineService.addExamineRecord(examineRecordSaveBO).getData();
                    crmPutinMoney.setExamineRecordId(examineData.getRecordId());
                    crmPutinMoney.setCheckStatus(examineData.getExamineStatus());
                } else {
                    crmPutinMoney.setCheckStatus(0);
                }
            }else{
                //设置审核状态为待审核
                crmPutinMoney.setCheckStatus(0);
            }*/
            updateById(crmPutinMoney);
//            actionRecordUtil.addRecord(crmPutinMoney.getPutinMoneyId(), CrmEnum.ROI_INVESTMENT, crmPutinMoney.getNumber());
        }
    }

    public void setPutinStatisticsData(CrmPutinStatistics crmPutinStatistics){

    }

    @Override
    public void updateInformation(CrmUpdateInformationBO updateInformationBO) {

    }

    @Override
    public CrmPutinMoney getPutinMoneyById(Integer putinMoneyId){
        CrmPutinMoney crmPutinMoney= baseMapper.queryCrmPutinMoneyById(putinMoneyId);
        String fileid=crmPutinMoney.getFileId();
        crmPutinMoney.setUrl("/adminFile/down/"+fileid);
        return crmPutinMoney;
    }

    public CrmPutinMoney getListPutinMoneyById(Integer putinMoneyId){
        CrmPutinMoney batchId= baseMapper.queryListById(putinMoneyId);
        String batchIds=batchId.getBatchId();
        batchId.setFileList(baseMapper.queryListCrmBatch(batchIds));

        return batchId;
    }

    /**
     * 根据投放平台与课程期数查询最小投放日期
     * @param platform 投放平台
     * @param coursePeriods 课程期数
     * @return
     */
    @Override
    public Date getMinPutinDateByPlatformAndCoursePeriods(String platform, String coursePeriods) {
        return baseMapper.getMinPutinDateByPlatformAndCoursePeriods(platform, coursePeriods);
    }

    /**
     * 根据投放平台与课程期数查询最大投放日期
     * @param platform 投放平台
     * @param coursePeriods 课程期数
     * @return
     */
    @Override
    public Date getMaxPutinDateByPlatformAndCoursePeriods(String platform, String coursePeriods) {
        return baseMapper.getMaxPutinDateByPlatformAndCoursePeriods(platform, coursePeriods);
    }

    /**
     * 根据投放平台、课程期数、投放日期查询投放金额表中的数据
     * @param putinPlatform 投放平台
     * @param coursePeriods 课程期数
     * @param putinDate 投放日期
     * @return
     */
    public CrmPutinMoney queryPutinDataByPlatformAndPeriodsAndDate(String putinPlatform, String coursePeriods, Date putinDate, Integer putinMoneyId){
        return baseMapper.queryPutinDataByPlatformAndPeriodsAndDate(putinPlatform,coursePeriods,putinDate,putinMoneyId);
    }

    /**
     * 根据投放平台与课程期数查询投放金额数据信息
     * @param platform 投放平台
     * @param coursePeriods 课程期数
     * @return
     */
    @Override
    public List<CrmPutinMoney> queryPutinMoneyDataByPlatformAndPeriods(String platform, String coursePeriods){
        return baseMapper.queryPutinMoneyDataByPlatformAndPeriods(platform, coursePeriods);
    }


    /**
     * 查询所有字段
     *
     * @return data
     */
    @Override
    public List<CrmModelFiledVO> queryField(Integer id) {
        return queryDefaultField();
    }

    /**
     * 下载导入模板
     *
     * @param response 线索id
     */
    @Override
    public void downloadExcel(HttpServletResponse response) throws IOException {
        List<CrmModelFiledVO> crmModelFiledList = queryField(null);
//        crmModelFiledList.removeIf(model -> Arrays.asList(FieldEnum.FILE, FieldEnum.CHECKBOX, FieldEnum.USER, FieldEnum.STRUCTURE).contains(FieldEnum.parse(model.getType())));
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("导入ROI投放金额");
        sheet.setDefaultRowHeight((short) 400);
        CellStyle textStyle = wb.createCellStyle();
        DataFormat format = wb.createDataFormat();
        textStyle.setDataFormat(format.getFormat("@"));
        for (int i = 0; i < crmModelFiledList.size(); i++) {
            CrmModelFiledVO crmModel = crmModelFiledList.get(i);
            if (FieldEnum.DATE.getType().equals(crmModel.getType())) {
                CellStyle dateStyle = wb.createCellStyle();
                DataFormat dateFormat = wb.createDataFormat();
                dateStyle.setDataFormat(dateFormat.getFormat(DatePattern.NORM_DATE_PATTERN));
                sheet.setDefaultColumnStyle(i, dateStyle);
            } else if (FieldEnum.DATETIME.getType().equals(crmModel.getType())) {
                CellStyle dateStyle = wb.createCellStyle();
                DataFormat dateFormat = wb.createDataFormat();
                dateStyle.setDataFormat(dateFormat.getFormat(DatePattern.NORM_DATETIME_PATTERN));
                sheet.setDefaultColumnStyle(i, dateStyle);
            } else {
                sheet.setDefaultColumnStyle(i, textStyle);
            }
            sheet.setColumnWidth(i, 20 * 256);
        }
        CellStyle cellStyle = wb.createCellStyle();
        HSSFRow titleRow = sheet.createRow(0);
        cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        Font font = wb.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 16);
        cellStyle.setFont(font);
        titleRow.createCell(0).setCellValue("ROI投放金额导入模板(*)为必填项");
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        titleRow.getCell(0).setCellStyle(cellStyle);
        CellRangeAddress region = new CellRangeAddress(0, 0, 0, crmModelFiledList.size() - 1);
        sheet.addMergedRegion(region);
        try {
            HSSFRow row = sheet.createRow(1);
            for (int i = 0; i < crmModelFiledList.size(); i++) {
                CrmModelFiledVO crmModel = crmModelFiledList.get(i);
                List<String> setting = crmModel.getSetting().stream().map(Object::toString).collect(Collectors.toList());
                // 在第一行第一个单元格，插入选项
                HSSFCell cell = row.createCell(i);
                // 普通写入操作
                cell.setCellValue(crmModel.getName() + (crmModel.getIsNull() == 1 ? "(*)" : ""));
                if (setting.size() != 0) {
                    String fieldName = "_" + crmModel.getFieldName();
                    HSSFSheet hidden = wb.createSheet(fieldName);
                    HSSFCell sheetCell;
                    for (int j = 0, length = setting.size(); j < length; j++) {
                        String name = setting.get(j);
                        HSSFRow sheetRow = hidden.createRow(j);
                        sheetCell = sheetRow.createCell(0);
                        sheetCell.setCellValue(name);
                    }
                    Name namedCell = wb.createName();
                    namedCell.setNameName(fieldName);
                    namedCell.setRefersToFormula(fieldName + "!$A$1:$A$" + setting.size());
                    CellRangeAddressList regions = new CellRangeAddressList(2, Integer.MAX_VALUE, i, i);
                    DVConstraint constraint = DVConstraint.createFormulaListConstraint(fieldName);
                    HSSFDataValidation dataValidation = new HSSFDataValidation(regions, constraint);
                    wb.setSheetHidden(wb.getSheetIndex(hidden), true);
                    sheet.addValidationData(dataValidation);
                }
            }
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename=roi_putin_monery_import.xls");
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            log.error("获取导入模板异常", e);
        } finally {
            wb.close();
        }
    }

    public List<CrmFieldSortVO> queryListHead(){
        List<CrmFieldSortVO> list = new ArrayList<>();
        list.add(new CrmFieldSortVO().setName("投放平台").setType(FieldEnum.SELECT.getType()).setFieldName("putinPlatform").setFormType(FieldEnum.SELECT.getFormType()));
        list.add(new CrmFieldSortVO().setName("大类").setType(FieldEnum.TEXT.getType()).setFieldName("category").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道充值金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道消耗金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("practicalPutinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道返点金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinRebatesMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道赔付金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("putinCompensateMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道转入金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("rollinMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("渠道转出金额").setType(FieldEnum.FLOATNUMBER.getType()).setFieldName("rolloutMoney").setFormType(FieldEnum.FLOATNUMBER.getFormType()));
        list.add(new CrmFieldSortVO().setName("备注").setType(FieldEnum.TEXT.getType()).setFieldName("remark").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("表单录入时间").setType(FieldEnum.DATE.getType()).setFieldName("putinFormDate").setFormType(FieldEnum.DATE.getFormType()));
        list.add(new CrmFieldSortVO().setName("创建时间").setType(FieldEnum.DATETIME.getType()).setFieldName("createTime").setFormType(FieldEnum.DATETIME.getFormType()));
        list.add(new CrmFieldSortVO().setName("创建人").setType(FieldEnum.TEXT.getType()).setFieldName("putinUserName").setFormType(FieldEnum.TEXT.getFormType()));
        list.add(new CrmFieldSortVO().setName("审核状态").setType(FieldEnum.TEXT.getType()).setFieldName("checkStatus").setFormType(FieldEnum.TEXT.getFormType()));

        return list;
    }

    /**
     * 导出
     * @param response resp
     * @param search   搜索对象
     */
    @Override
    public void exportExcel(HttpServletResponse response, CrmRoiSearchBO search) {
        if (search.getPutinPlatform()!=null && !search.getPutinPlatform().equals("")) {
            String allPutinPlatform = search.getPutinPlatform();
            search.setPutinPlatforms(allPutinPlatform.split(","));
        }
        List<CrmPutinMoney> crmPutinMoneyList = queryPageList(search).getList();
        List<Map<String, Object>> dataList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(crmPutinMoneyList)){
            for(CrmPutinMoney crmPutinMoney : crmPutinMoneyList){
                Map<String, Object> map = new HashMap();
                map.put("putinPlatform",crmPutinMoney.getPutinPlatform());
                map.put("category",crmPutinMoney.getCategory());
                map.put("putinMoney",crmPutinMoney.getPutinMoney());
                map.put("practicalPutinMoney",crmPutinMoney.getPracticalPutinMoney());
                map.put("putinRebatesMoney",crmPutinMoney.getPutinRebatesMoney());
                map.put("putinCompensateMoney",crmPutinMoney.getPutinCompensateMoney());
                map.put("rollinMoney",crmPutinMoney.getRollinMoney());
                map.put("rolloutMoney",crmPutinMoney.getRolloutMoney());
                map.put("remark",crmPutinMoney.getRemark());
                map.put("putinFormDate",crmPutinMoney.getPutinFormDate());
                map.put("createTime",crmPutinMoney.getCreateTime());
                map.put("putinUserName",crmPutinMoney.getPutinUserName());
                if (crmPutinMoney.getCheckStatus()==1){
                    map.put("checkStatus","通过");
                }else if (crmPutinMoney.getCheckStatus()==3){
                    map.put("checkStatus","审核中");
                }else if(crmPutinMoney.getCheckStatus()==2){
                    map.put("checkStatus","拒绝");
                }else if (crmPutinMoney.getCheckStatus()==0){
                    map.put("checkStatus","待审核");
                }else if (crmPutinMoney.getCheckStatus()==4){
                    map.put("checkStatus","未提交");
                }
                dataList.add(map);
            }
        }
        try (ExcelWriter writer = ExcelUtil.getWriter()) {
            List<CrmFieldSortVO> headList = queryListHead();
            headList.forEach(head -> writer.addHeaderAlias(head.getFieldName(), head.getName()));
            writer.merge(headList.size() - 1, "ROI投入金额信息");
            if (dataList.size() == 0) {
                Map<String, Object> record = new HashMap<>();
                headList.forEach(head -> record.put(head.getFieldName(), ""));
                dataList.add(record);
            }
            writer.setOnlyAlias(true);
            writer.write(dataList, true);
            writer.setRowHeight(0, 30);
            writer.setRowHeight(1, 20);
            for (int i = 0; i < headList.size(); i++){
                writer.setColumnWidth(i, 20);
            }
            Cell cell = writer.getCell(0, 0);
            CellStyle cellStyle = cell.getCellStyle();
            cellStyle.setFillForegroundColor(IndexedColors.SKY_BLUE.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            Font font = writer.createFont();
            font.setBold(true);
            font.setFontHeightInPoints((short) 16);
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);
            //自定义标题别名
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            response.setHeader("Content-Disposition", "attachment;filename=roi_putin_monery.xls");
            ServletOutputStream out = response.getOutputStream();

            writer.flush(out);
        } catch (Exception e) {
            log.error("导出ROI投放金额错误：", e);
        }
    }


    /**
     * 查询投放平台
     *
     */
    public List<String> querySource(){
        List<String> result = new ArrayList<>();
        QueryWrapper<CrmField> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("label", 1);
        queryWrapper.eq("field_name", "source");
        List<CrmField> fieldList = crmFieldMapper.selectList(queryWrapper);
        if(CollectionUtil.isNotEmpty(fieldList)){
            CrmField crmField = fieldList.get(0);
            String options = crmField.getOptions();
            if(StringUtils.isNotBlank(options)){
                String[] array = options.split(",");
                result = Arrays.asList(array);
            }
            return result;
        }else{
            return result;
        }
    }

    public CrmPutinMoney queryCrmPutinMoneyById(Integer putinMoneyId){
        return baseMapper.queryCrmPutinMoneyById(putinMoneyId);
    }

    /**
     * 修改ROI审批状态，审批通过的ROI数据更新到ROI统计中
     * @param crmPutinMoney
     */
    public void updateCheckStatus(CrmPutinMoney crmPutinMoney){
        baseMapper.updateCheckStatus(crmPutinMoney);

        //判断ROI数据的审批状态为通过
        if(BeanUtil.isNotEmpty(crmPutinMoney) && crmPutinMoney.getCheckStatus() == 1){

            // 加盟商ROI审核通过后重新计算余额
            CrmAllianceBusinessBalance crmAllianceBusinessBalance = crmAllianceBusinessBalanceService.queryDataByDeptId(crmPutinMoney.getDeptId(),crmPutinMoney.getPutinPlatform());
            if (crmAllianceBusinessBalance!=null) {
                crmAllianceBusinessBalance.setBalance(crmAllianceBusinessBalance.getBalance().subtract(crmPutinMoney.getPracticalPutinMoney()));
                crmAllianceBusinessBalanceService.updateById(crmAllianceBusinessBalance);
            }
            // 总部ROI审核通过后重新计算余额
            CrmHeadquartersBusinessBalance crmHeadquartersBusinessBalance = crmHeadquartersBusinessBalanceService.queryDataByDeptId(crmPutinMoney.getDeptId(),crmPutinMoney.getPutinPlatform());
            if (crmHeadquartersBusinessBalance!=null) {

                //实际消耗    余额+赔付金额+转入金额-转出金额-消耗金额
                /*BigDecimal headMoney=crmPutinMoney.getPracticalPutinMoney().subtract(crmPutinMoney.getPutinRebatesMoney()).
                        subtract(crmPutinMoney.getPutinCompensateMoney()).subtract(crmPutinMoney.getRolloutMoney()).add(crmPutinMoney.getRollinMoney());
                crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusinessBalance.getBalance().subtract(headMoney));*/
                BigDecimal xiaoHao = crmPutinMoney.getPutinCompensateMoney().add(crmPutinMoney.getRollinMoney()).subtract(crmPutinMoney.getRolloutMoney()).subtract(crmPutinMoney.getPracticalPutinMoney());
                crmHeadquartersBusinessBalance.setBalance(crmHeadquartersBusinessBalance.getBalance().add(xiaoHao));
                crmHeadquartersBusinessBalanceService.updateById(crmHeadquartersBusinessBalance);
            }
            //根据投放平台与课程期数没有查询到统计数据则做新增 - 新数据
            CrmPutinStatistics newCrmPutinStatistics = crmPutinStatisticsService.queryStatisticsByPlatformAndPutinDormData(crmPutinMoney.getPutinPlatform(),crmPutinMoney.getPutinFormDate());
            if(newCrmPutinStatistics != null){
                //设置渠道赔付金额
                newCrmPutinStatistics.setPutinCompensateMoney(newCrmPutinStatistics.getPutinCompensateMoney().add(crmPutinMoney.getPutinCompensateMoney()));
                //设置渠道返点金额
                newCrmPutinStatistics.setPutinRebatesMoney(newCrmPutinStatistics.getPutinRebatesMoney().add(crmPutinMoney.getPutinRebatesMoney()));
                //设置渠道充值金额
                newCrmPutinStatistics.setPutinMoney(newCrmPutinStatistics.getPutinMoney().add(crmPutinMoney.getPutinMoney()));
                //设置渠道消耗金额
                newCrmPutinStatistics.setPracticalPutinMoney(newCrmPutinStatistics.getPracticalPutinMoney().add(crmPutinMoney.getPracticalPutinMoney()));
                //设置实际消耗金额
                BigDecimal calculateMoney = newCrmPutinStatistics.getPutinMoney().subtract(newCrmPutinStatistics.getPracticalPutinMoney()).add(newCrmPutinStatistics.getPutinRebatesMoney()).add(newCrmPutinStatistics.getPutinCompensateMoney());
                //实际消耗金额=充值金额-(充值金额-消耗金额+返点金额+赔付金额)
                newCrmPutinStatistics.setActualConsumptionMoney(newCrmPutinStatistics.getPutinMoney().subtract(calculateMoney));

                SpringUtils.getBean(CrmPutinStatisticsMapper.class).updateById(newCrmPutinStatistics);

            }else{
                newCrmPutinStatistics = new CrmPutinStatistics();
                //设置投放统计表中投放金额
                newCrmPutinStatistics.setPutinMoney(crmPutinMoney.getPutinMoney());
                //设置投放统计表中投放平台
                newCrmPutinStatistics.setPutinPlatform(crmPutinMoney.getPutinPlatform());
                //设置表单录入时间
                newCrmPutinStatistics.setPutinFormDate(crmPutinMoney.getPutinFormDate());
                //设置投放统计表中实际投放金额
                newCrmPutinStatistics.setPracticalPutinMoney(crmPutinMoney.getPracticalPutinMoney());
                //设置渠道赔付金额
                newCrmPutinStatistics.setPutinCompensateMoney(crmPutinMoney.getPutinCompensateMoney());
                //设置渠道返点金额
                newCrmPutinStatistics.setPutinRebatesMoney(crmPutinMoney.getPutinRebatesMoney());
                //设置渠道充值金额
                newCrmPutinStatistics.setPutinMoney(crmPutinMoney.getPutinMoney());
                //设置渠道消耗金额
                newCrmPutinStatistics.setPracticalPutinMoney(crmPutinMoney.getPracticalPutinMoney());
                //设置实际消耗金额
                BigDecimal calculateMoney = newCrmPutinStatistics.getPutinMoney().subtract(newCrmPutinStatistics.getPracticalPutinMoney()).add(newCrmPutinStatistics.getPutinRebatesMoney()).add(newCrmPutinStatistics.getPutinCompensateMoney());
                //实际消耗金额=充值金额-(充值金额-消耗金额+返点金额+赔付金额)
                newCrmPutinStatistics.setActualConsumptionMoney(newCrmPutinStatistics.getPutinMoney().subtract(calculateMoney));
                //设置合同成交数量
                newCrmPutinStatistics.setContractDealCount(0);
                //设置回款成交金额
                newCrmPutinStatistics.setReceivablesDealMoney(new BigDecimal(0));
                //设置初始ROI：若实际消耗金额小于等于0，则初始ROI为空，否则为0
                if(newCrmPutinStatistics.getActualConsumptionMoney().compareTo(new BigDecimal(0)) == 1){
                    newCrmPutinStatistics.setCurrentPeriodRoi("0");
                }
                //新增统计表数据信息
                SpringUtils.getBean(CrmPutinStatisticsMapper.class).insert(newCrmPutinStatistics);
            }
        }
    }

}
